package com.spring.housing.service.Login;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.netflix.client.http.HttpRequest;
import com.spring.housing.acceptType.PageParams;
import com.spring.housing.constant.Constants;
import com.spring.housing.constant.DeliverTypes;
import com.spring.housing.deliver.QueryForOderNo;
import com.spring.housing.feign.ComsumerOpenfeign;
import com.spring.housing.redisConfig.DistributedRedisLock;
import com.spring.housing.returnType.CommenResult;
import com.spring.housing.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;


@Slf4j
@Service
public class LoginServer {
    @Autowired
    RedisTemplate redisTemplate;
    //真实查询快递
    @Autowired
    QueryForOderNo queryForOderNo;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    ComsumerOpenfeign comsumerOpenfeign;
    /**
     * 1002为免费接口支持查询天天、申通、圆通、百世 8001全功能
     */

    public CommenResult logincheck(PageParams params){
        CommenResult getinfo = comsumerOpenfeign.getinfo(params);
        return getinfo;
    }
    public String logincheck2(){
        return  comsumerOpenfeign.getinfo();
    }

    public CommenResult newsInfo(PageParams params) {
        return comsumerOpenfeign.newsInfo(params);
    }

    public CommenResult locationArr() {
        String sql="SELECT  a.house_main,a.house_id,a.location_x,a.location_y from area_house a GROUP BY a.house_main";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        List<Map<String,Object>> res = new ArrayList<>();
        for (Map li:list) {
            Map<String,Object> m = new ConcurrentHashMap();
            m.put("value",li.get("house_main"));
            m.put("key",li.get("house_id").toString().substring(0,3));
            m.put("location",new String[]{li.get("location_x").toString(),li.get("location_y").toString()});
            if(redisTemplate.opsForValue().get(Constants.LOCATION) !=null){
                redisTemplate.delete(Constants.LOCATION);
            }
           redisTemplate.opsForValue().set(Constants.LOCATION,new String[]{li.get("location_x").toString(),li.get("location_y").toString()},125,TimeUnit.MINUTES);
            res.add(m);
        }
        List<Map<String, Object>> userInfo = (List<Map<String, Object>>) redisTemplate.opsForValue().get(Constants.UserINFO);
        String call = userInfo.get(0).get("phone").toString();
        List<Map<String, Object>> list1 = jdbcTemplate.queryForList("select count(*) count from message_center where r_phone =? and state =1", call);

        res.addAll(list1);
        return new CommenResult(200,"位置信息查询成功!",res);
    }


    public CommenResult getddcx(PageParams params,String dPort) throws Exception {
     if(params.getParam().get("type").equals("")){
         return  new CommenResult(201,"请选择订单类型","");
     }
        if(params.getParam().get("query").equals("")){
            return  new CommenResult(201,"订单号为空","");
        }
        String res;
        //顺丰快递
     if(params.getParam().get("type").toString().equals("SF")){
         res= queryForOderNo.orderOnlineByJson2(Integer.parseInt(params.getParam().get("query").toString().split(",")[0]),params.getParam().get("type").toString(),params.getParam().get("query").toString().split(",")[1],Integer.parseInt(dPort));
     }
     //其他快递
     else{
         res= queryForOderNo.orderOnlineByJson(params.getParam().get("type").toString(),params.getParam().get("query").toString(),Integer.parseInt(dPort));
     }
     List<Map<String,String>> dateList =new ArrayList<>();
        Map<String,Object> parse = (Map<String, Object>) JSONUtils.parse(res);
        for (DeliverTypes.DeliverTypeseg v:DeliverTypes.DeliverTypeseg.values()) {
          if(parse.get("ShipperCode").toString().equals(v.getType())) {
              parse.put("trans",v.getName());
          }
        }
        ArrayList<String> color = new ArrayList<>();
        List<Map<String,String>> l= (List<Map<String, String>>) parse.get("Traces");
        for (int i = 0; i <l.size() ; i++) {
            if((i/3)<=0){
                color.add("#0bbd87");
            }

            else {
                if(i==l.size()){
                    color.add("greenyellow");
                }else
                color.add("gold");
            }

        }

        parse.put("color",color);
     if(parse.get("Reason")!=null){
         return  new CommenResult(200,"快递信息查询失败!暂时查询不到该信息",parse);
     }

        return  new CommenResult(200,"快递信息查询成功!",parse);

    }

    public CommenResult getmessageCount() {
        List<Map<String,String>> o = (List<Map<String, String>>) redisTemplate.opsForValue().get(Constants.UserINFO);
        return new CommenResult(200,"查询用户信息成功!",o);
    }

    public CommenResult getmessage(PageParams params) {
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select descs,s_phone,s_name,date_format(e_date,'%Y-%m-%d') as e_date,r_phone,r_name,desc_img,state,s_sex from message_center where r_phone = ? and state =1 order by 5 desc", params.getParam().get("phone").toString());
        return new CommenResult(200,"查询消息成功!",list);
    }

    public static void main(String[] args) {
        Map m = new HashMap();
        m.put("aa","aaaq");
        System.out.println(m.keySet().toArray()[0]);

        String a ="￥:20";
        System.out.println(a.split(":")[1]);
    }

    public CommenResult getLocations() {
        //定位时保存在redis中的位置信息
      List<Map<String,String>>res= (List<Map<String, String>>) redisTemplate.opsForValue().get(Constants.LOCATION);
        return new CommenResult(200,"定位成功!",res);
    }
@Transactional
    public CommenResult sendMessage(PageParams page) {
        //1为发送2为已读
        if(page.getParam().get("type").toString().equals("1")){
            String  sql ="insert into  message_center(descs,s_phone,s_name,e_date,r_phone,r_name,desc_img,state,s_sex) values(?,?,?,?,?,?,?,?,?)";
            List aadParams=new ArrayList();
            aadParams.add(page.getParam().get("r_desc").toString());
            aadParams.add(page.getParam().get("r_phone").toString());
            aadParams.add(page.getParam().get("r_name").toString());
            aadParams.add(new Date());
            aadParams.add(page.getParam().get("s_phone").toString());
            aadParams.add(page.getParam().get("s_name").toString());
            aadParams.add(page.getParam().get("desc_img").toString());
            aadParams.add("1");
            aadParams.add(page.getParam().get("r_sex").toString());
            int update = jdbcTemplate.update(sql, aadParams.toArray());
            if(update>0){
                jdbcTemplate.update("update message_center set state =0 where date_format(e_date,'%Y-%m-%d')=?",page.getParam().get("e_date").toString());
            }
            else {
                //发送失败进行事务回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                log.info("消息发送失败!事务以回滚!");
                return  new CommenResult(201,"消息发送失败！","");
            }

            return  new CommenResult(200,"已通知"+aadParams.add(page.getParam().get("s_name").toString())+page.getParam().toString(),page.getParam().get("r_name").toString());

        }
        else {
            jdbcTemplate.update("update message_center set state =0 where date_format(e_date,'%Y-%m-%d')=?",page.getParam().get("e_date").toString());
            return  new CommenResult(200,"消息已读!",page.getParam().get("r_name").toString());

        }
       }

    public CommenResult ofckb(PageParams params) {
        return comsumerOpenfeign.ofckb( params);
    }

    public CommenResult ofckbSubOrder(PageParams page) {
        String sql="insert into d_ofc(order_phone,order_code,state,descs,destination,money,area,date) values(?,?,?,?,?,?,?,?)";
        List<Map<String,String>> o = (List<Map<String, String>>) redisTemplate.opsForValue().get(Constants.UserINFO);
        String adress = o.get(0).get("adress");
        int res = jdbcTemplate.update(sql, page.getParam().get("name").toString(), page.getParam().get("code").toString(),
                "1", page.getParam().get("aadress").toString(), page.getParam().get("destination").toString(),
                page.getParam().get("money").toString(), adress, new Date()
        );
        if(res>0){
            return  new CommenResult(200,"发布成功!","成功!");
        }
        else {
            return  new CommenResult(500,"发布失败!","失败!");

        }

    }
//抢单 两台服务负载均衡
    public CommenResult acceptOder(PageParams page) {

        return comsumerOpenfeign.acceptOder(page);
      }


    public CommenResult queryClzx(PageParams page) {
        List<Map<String,String>> users= (List<Map<String, String>>) redisTemplate.opsForValue().get(Constants.UserINFO);
        String phone = users.get(0).get("phone");

        String sql="select a.order_phone,a.order_code,a.descs,a.destination,a.money,a.area,date_format(a.acc_date,'%Y-%m-%d'),a.own_phone,a.pass_date ,b.`call` from \n" +
               "               (select order_phone,order_code,state,descs,destination,money,area,acc_date,own_phone,pass_date from handel_center) a\n" +
               "               join (select phone,`call` from user where )b on a.order_phone=b.phone" +
               "where (own_phone=? or order_phone=?) and state =1";
        List aa = new ArrayList();
        aa.add(phone);
        aa.add(phone);
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, aa.toArray());
        Map m = new HashMap();
        m.put("curentOprator",phone);
        list.add(m);
        return  new CommenResult(200,"订单处理信息查询成功！",list);
    }

    public CommenResult handelClzx(PageParams page) {
        String sql ="update d_ofc set state =0 where order_code=?";
        //跟新状态值
        String sql2 ="update handel_center set state =0 where order_code=?";
        jdbcTemplate.update(sql,page.getParam().get("order_code"));
        jdbcTemplate.update(sql2,page.getParam().get("order_code"));
        //发送消息给用户通知货物已经取到了
//发送人的信息获取
        Map<String, Object> map = jdbcTemplate.queryForMap("select call,sex from user where phone =?", page.getParam().get("own_phone"));
        List<Object> m = new ArrayList<>();
        m.add("客官您好，您的物品已送达,记得好评哦~^_^");
        m.add(page.getParam().get("own_phone"));
        m.add(map.get("call").toString());
        m.add(new Date());
        m.add(page.getParam().get("order_phone"));
        m.add(page.getParam().get("call"));
        m.add("https://img1.baidu.com/it/u=3680320999,4108379159&fm=253&fmt=auto&app=138&f=PNG?w=518&h=500");
        m.add("1");
        m.add(map.get("sex").toString());
        String  sql1 ="insert into  message_center(descs,s_phone,s_name,e_date,r_phone,r_name,desc_img,state,s_sex) values(?,?,?,?,?,?,?,?,?)";
       return new CommenResult(200,"订单处理信息处理成功！","");
    }

}
